package lance.honeydew.util;

import java.io.*;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class FileUtil {

	private static final Logger logger = Logger.getLogger(FileUtil.class);

	public static final String DEFAULT_ENCODING = "UTF-8";

	public static void copyStream(InputStream from, OutputStream to)
			throws IOException {
		copyStream(from, to, 1024);
	}

	public static void copyStream(InputStream from, OutputStream to,
			int bufferSize) throws IOException {
		BufferedInputStream bIn = new BufferedInputStream(from);
		BufferedOutputStream bOut = new BufferedOutputStream(to);
		byte[] b = new byte[bufferSize];
		int len = 0;
		while ((len = bIn.read(b)) > 0) {
			bOut.write(b, 0, len);
		}
		bOut.flush();
	}

	public static void close(Closeable stream) {
		if (stream == null)
			return;
		try {
			stream.close();
		} catch (Exception e) {
			if (logger.isEnabledFor(Level.ERROR))
				logger.error("unable to close given stream.", e);
		}
	}

	/* Delete File */
	public static void removeFile(String filePath) {
		File f = new File(filePath);
		f.delete();
	}

	/* Read File */
	public static byte[] readFile(String filePath) throws Exception {
		File file = new File(filePath.trim());
		return readFile(file);
	}

	public static byte[] readFile(File file) throws Exception {
		byte[] data = null;
		FileInputStream fis = null;
		ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
		try {
			if (logger.isDebugEnabled())
				logger.debug("readFile: " + file.getAbsolutePath());
			fis = new FileInputStream(file);
			copyStream(fis, bos);
			data = bos.toByteArray();
		} catch (Exception e) {
			if (logger.isEnabledFor(Level.ERROR))
				logger.error("readFile() failed.", e);
			throw e;
		} finally {
			close(fis);
			close(bos);
		}
		return data;
	}

	/* Write File */
	public static void writeFile(InputStream is, String filePath)
			throws Exception {
		writeFile(is, new File(filePath.trim()));
	}

	public static void writeFile(InputStream is, File destFile)
			throws Exception {
		copyStream(is, new FileOutputStream(destFile));
	}
	
	/**
	 * web file upload
	 * 
	 * @param file 
	 * @param fileName 
	 * @param filesDirectory 
	 * @throws IOException 
	 */
	public static void saveFile(File file, String fileName, String filesDirectory) {
        FileInputStream in = null;
        FileOutputStream out = null;
         
        File dir = new File(filesDirectory);
        if ( !dir.exists() )
           dir.mkdirs();
        
        String targetPath =  dir.getPath() + File.separator + fileName;
		File destinationFile = new File(targetPath);
        
        try {
        	in = new FileInputStream(file);
            out = new FileOutputStream(destinationFile);
            int c;
 
            while ((c = in.read()) != -1) {
                out.write(c);
            }            	 
        }catch(Exception e){
        	logger.debug(e);
        }finally {
            if (in != null) {
                try {
					in.close();
				} catch (IOException e) {
					logger.debug(e);
				}
            }
            if (out != null) {
                try {
					out.close();
				} catch (IOException e) {
					logger.debug(e);
				}
            }
        }
         
    }
}
